package com.yunshang.shoppingmall.config;

import com.yunshang.shoppingmall.entity.Admin;
import com.yunshang.shoppingmall.entity.UserRolePrivileges;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 登录拦截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Admin admin = (Admin) request.getSession().getAttribute("admin");

        String ss = request.getRequestURI();
        if(ss.startsWith("/Finace/")){
            ss="/Finace/*";
        }
        if (admin == null) {
            response.sendRedirect("/sysLogin");
            return false;
        }
        boolean flag = false;
        Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute("map");
        int URLroleId = (int) map.get(ss);
        ss=null;
        if (admin != null) {
            int adminId = admin.getAdminId();
            List<UserRolePrivileges> userRolePrivilegesList = (List<UserRolePrivileges>) request.getSession().getAttribute("userRolePrivilegesList");

            for (int i = 0; i < userRolePrivilegesList.size(); i++) {
                int adminRoleId = userRolePrivilegesList.get(i).getRoleId();
                if (adminRoleId == URLroleId) {
                    flag = true;
                }
            }
if(!flag){
    response.sendRedirect("/403.html");
}
            return flag;

        } else {
            response.sendRedirect("/sysLogin");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);

    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }


}
